var createError = require('http-errors')
var express = require('express')
var path = require('path')
var logger = require('morgan')
var expressLayouts = require('express-ejs-layouts');
var settings = require('./settings')
var session = require('express-session')
var mongodb = require('connect-mongo')(session)


var app = express()
app.use(expressLayouts)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use(session({
    secret: settings.secret,
    store: new mongodb({
        url: settings.url,
        dbName: settings.dbname,
    }),
}))



app.use(function (req, res, next) {
    res.locals.appUtl = req.url
    res.locals.Welcome = function () {
        return req.headers
    }
    next()
})


var indexRouter = require('./routes/index')
var userRouter = require('./routes/user')
var articleRouter = require('./routes/article')

app.use(function (req, res, next) {
    res.locals.user = req.session.user
    var err = req.session.user ? '' : 'register error'
    var success = req.session.user ? 'register success' : ''

    res.locals.error = err.length ? err : ''
    res.locals.success = success.length ? success : ''
    next()
})

app.use('/', indexRouter)
app.use('/', userRouter)
app.use('/', articleRouter)


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message
    res.locals.error = req.app.get('env') === 'development' ? err : {}

    // render the error page
    res.status(err.status || 500)
    res.render('error')
})


app.listen(3000, function () {
    console.log('Server start at port 3000')
})